package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.common.R;
import com.reggie.entity.User;
import com.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 移动端用户登录的功能
 * @program: reggie
 * @author:
 * @create: 2022-10-12 08:39
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     *
     * */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        //使用验证码进行登录（需完善）

        //判断用户是否是新用户
        String phone = (String) map.get("phone");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = userService.getOne(wrapper);
        if (user==null){
            //用户未注册,会自动生成id的值，然后插入到User表中，不需要在进行获取表中的id的值
            user=new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        //用户已经注册
        return R.success(user);


    }

    /**
     * 退出登录
     * */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功！");
    }
}
